import { useEffect, useRef, useState } from "react";
import {
  Form,
  Row,
  Col,
  Button,
  Space,
  Input,
  Cascader,
  message,
  Spin,
} from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { changeupdateState } from "@/store/modules/assStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";

import {
  getCpuList,
  getCpuSeries,
  uploadCpuInfo,
  updateCpuInfo,
} from "@/api/api_cpu";
const type = "CPU";

interface ChildMethods {
  handleUpload: () => void;
}

interface seriesType {
  code_name?: string;
  manufacturers: string;
  series: string;
  _id: string;
  __v: number;
}

interface Option {
  value: string;
  label: string;
  children?: Option[];
}
//获取CPU系列
const Cpu_Intel: Option[] = [];
const Cpu_AMD: Option[] = [];
const CpuList = (manufacturers: string) => {
  getCpuSeries(manufacturers).then((res) => {
    const list = (res as seriesType[]).map((item) => {
      return { value: item.series, label: item.series, children: [] };
    });

    if (manufacturers === "Intel") {
      Cpu_Intel.push(...list);
      // console.log(list);

      processAsyncRequests(res)
        .then((results) => {
          // 所有请求成功完成
          // console.log(results);

          const intelList = results.map((item: seriesType[]) => {
            return item.map((item_i) => {
              return { value: item_i.code_name, label: item_i.code_name };
            });
          });

          intelList.forEach((item, index) => {
            Cpu_Intel[index].children = item;
          });
        })
        .catch((error) => {
          // 请求中有一个或多个失败
          console.error(error);
        });
    } else {
      Cpu_AMD.push(...list);
      processAsyncRequests(res)
        .then((results) => {
          // 所有请求成功完成
          // console.log(results);
          const amdList = results.map((item: seriesType[]) => {
            return item.map((item_i) => {
              return { value: item_i.code_name, label: item_i.code_name };
            });
          });

          amdList.forEach((item, index) => {
            Cpu_AMD[index].children = item;
          });
        })
        .catch((error) => {
          // 请求中有一个或多个失败
          console.error(error);
        });
    }
  });
};

if (Cpu_Intel.length === 0) {
  CpuList("Intel");
}
if (Cpu_AMD.length === 0) {
  CpuList("AMD");
}

const CpuCodeList: Option[] = [
  {
    value: "Intel",
    label: "Intel",
    children: Cpu_Intel,
  },
  {
    value: "AMD",
    label: "AMD",
    children: Cpu_AMD,
  },
];
// 处理异步请求
const processAsyncRequests = (items: seriesType[]) => {
  return Promise.all(
    items.map((item) => {
      return getCpuList(item.manufacturers, item.series)
        .then((result) => {
          // 处理请求成功的情况
          return result;
        })
        .catch((error) => {
          throw error;
        });
    })
  );
};

function CpuItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  useEffect(() => {
    if (!isAdd) {
      const {
        manufacturers,
        series,
        code_name,
        cores,
        clock_speed,
        threads,
        socket_type,
        L2,
        L3,
        pro_tech,
        price,
        score,
      } = assInfo;
      const data = {
        cpuManufacturer: [manufacturers, series, code_name],
        Cores: cores,
        Threads: threads,
        ClockSpeed: clock_speed,
        SocketType: socket_type,
        L2,
        L3,
        ProTech: pro_tech,
        score,
        price,
      };

      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);

  //CPU TSX
  const CPU = {
    MANUFACTURERS: (
      <Form.Item
        name="cpuManufacturer"
        label="厂商"
        rules={[
          {
            type: "array",
            required: true,
            message: "Please select your cpuManufacturer!",
          },
        ]}
      >
        <Cascader options={CpuCodeList} />
      </Form.Item>
    ),
    CORES: (
      <Form.Item
        name="Cores"
        label="CPU核心数"
        rules={[{ required: true, message: "Please input Cores!" }]}
      >
        <Input suffix="核心" />
      </Form.Item>
    ),
    THREADS: (
      <Form.Item
        name="Threads"
        label="CPU线程数"
        rules={[{ required: true, message: "Please input Threads!" }]}
      >
        <Input suffix="线程" />
      </Form.Item>
    ),
    CLOCK_SPEED: (
      <Form.Item
        name="ClockSpeed"
        label="CPU主频"
        rules={[{ required: true, message: "Please input Clock Speed!" }]}
      >
        <Input suffix="GHz" />
      </Form.Item>
    ),
    SCOKET_TYPE: (
      <Form.Item
        name="SocketType"
        label="插槽类型"
        rules={[{ required: true, message: "Please select SocketType!" }]}
      >
        <Input />
      </Form.Item>
    ),
    L2: (
      <Form.Item
        name="L2"
        label="二级缓存"
        rules={[{ required: true, message: "Please input L2!" }]}
      >
        <Input suffix="MB" />
      </Form.Item>
    ),
    L3: (
      <Form.Item
        name="L3"
        label="三级缓存"
        rules={[{ required: true, message: "Please input L3!" }]}
      >
        <Input suffix="MB" />
      </Form.Item>
    ),
    PROCESSTECHNOLOGY: (
      <Form.Item
        name="ProTech"
        label="制程工艺"
        rules={[{ required: true, message: "Please input ProTech!" }]}
      >
        <Input suffix="纳米" />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };
  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();

    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加CPU信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.cpuManufacturer[0],
        series: values.cpuManufacturer[1],
        code_name: values.cpuManufacturer[2],
        cores: values.Cores,
        threads: values.Threads,
        clock_speed: values.ClockSpeed,
        socket_type: values.SocketType,
        L2: values.L2,
        L3: values.L3,
        pro_tech: values.ProTech,
        img_url_arr,
        price: parseFloat(values.price),
        score: parseFloat(values.score),
      };
      console.log(info);

      if (!isAdd) {
        await updateCpuInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadCpuInfo(info);
        message.success("添加成功");
      }
      
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{CPU.MANUFACTURERS}</Col>
          <Col span={12}>{CPU.CORES}</Col>
          <Col span={12}>{CPU.THREADS}</Col>
          <Col span={12}>{CPU.CLOCK_SPEED}</Col>
          <Col span={12}>{CPU.SCOKET_TYPE}</Col>
          <Col span={12}>{CPU.L2}</Col>
          <Col span={12}>{CPU.L3}</Col>
          <Col span={12}>{CPU.PROCESSTECHNOLOGY}</Col>
          <Col span={12}>{CPU.SCORE}</Col>
          <Col span={12}>{CPU.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {isAdd ? "添加" : "更新"}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default CpuItem;
